<template>
  <div>
    <a-button
      type="primary"
      style="margin-right:10px;font-size:14px;"
      @click="showMoreStudent()"
    >添加学员</a-button>
    <a-button
      style="margin-right:10px;font-size:14px;"
      :disabled="!hasSelected"
      @click="showClass(actionAll)"
    >调至其他班</a-button>
    <a-button
      style="margin-right:10px;font-size:14px;"
      :disabled="!hasSelected"
      @click="remove(actionAll)"
    >移出本班</a-button>
    <a-table
      :columns="columns"
      :dataSource="loadData"
      :pagination="false"
      class="user_management_table"
      style="margin-top:20px;border:1px solid #e8e8e8;"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="name" slot-scope="text,record">
        <a @click="$router.push({name:'student_Info',query:{id:record.id}})">{{text}}</a>
      </span>
      <span slot="action" slot-scope="text,record">
        <a @click="showClass([record.id])">调至其他班</a>
        <a-divider type="vertical" />
        <a @click="remove([record.id])">移出本班</a>
      </span>
      <div slot="shengyu" slot-scope="text,record">
        <div v-if="record.surplus_clas_hour">
          <div v-if="record.surplus_clas_hour.hour||Number(record.surplus_clas_hour.hour)==0" style="margin-bottom:10px;">
            {{record.surplus_clas_hour.hour}}课时
            <span v-if="record.hour_due_time&&courseCalidity" style="color: rgb(236, 75, 53);">
              (已于{{record.hour_due_time}}到期)
            </span>
          </div>    
          <div v-if="record.surplus_clas_hour.day||Number(record.surplus_clas_hour.day)==0">{{record.surplus_clas_hour.day}}天</div> 
        </div> 
        <div v-else>--</div>
      </div>
    </a-table>
    <a-modal
      title="学员列表"
      :visible="visible"
      @cancel="handleCancel"
      @ok="handleOk"
      :confirmLoading="SconfirmLoading"
      width="700px"
      :bodyStyle="{'padding-bottom':0}"
    >
      <a-input placeholder="请输入学员姓名/手机号" v-model="keywords" style="width:200px;" />
      <s-table
        ref="studentTable"
        :rowKey="(record) => record.id"
        :columns="studentColumns"
        :data="studentLoadData"
        :loading="studentLoading"
        class="user_management_table"
        style="margin:20px 0 ;position:relative;max-height:400px;overflow-y:auto"
        :rowSelection="{ selectedRowKeys: SselectedRowKeys, onChange: SonSelectChange }"
      >
        <span slot="sex" slot-scope="text,record">{{record.sex==1?'男':record.sex==2?'女':''}}</span>
      </s-table>
      <div style="position:absolute;bottom:15px;">已选择&nbsp;{{SselectedRowKeys.length}}&nbsp;人</div>
    </a-modal>
    <a-modal title="选择班级" :visible="classModel" @cancel="classChoiceCancel" :footer="null">
      选择班级：
      <a-select v-model="choiceClassID" style="width:200px;" placeholder="请选择目标班级">
        <a-select-option
          v-for="(item,index) in classSelect"
          :key="index"
          :value="item.id"
          v-if="item.id!==Number($route.query.id)"
        >{{item.name}}</a-select-option>
      </a-select>
      <br />
      <br />
      <div style="text-align:right;">
        <a-button
          type="primary"
          style="margin-right:10px;"
          :disabled="!choiceClassID"
          @click="moveClass(actionAll)"
        >确定</a-button>
        <a-button @click="classChoiceCancel">取消</a-button>
      </div>
    </a-modal>
     <a-modal
      title="学员冲突"
      :visible="studentVisible"
      @ok="studentOk"
      @cancel="studentVisible=false"
      okText="忽略冲突"
       okType="danger"
      :zIndex="1100"
    >
      <div class="title">
        <div class="title-left"><a-icon type="warning" style="margin-right:8px;color:#fdaba9;" theme="filled"/>排课冲突提示</div>
        <div class="title-right" style="cursor: pointer;" @click="addConflictTest">检测冲突</div>
      </div>
      <div class="datas">
          <div style="color:#f14133;"><a-icon type="warning" style="margin-right:8px;" theme="filled"/>学员冲突({{conflict.length}})</div>
          <div v-for="(item,index) in conflict" :key="index" style="padding-left:10px;margin-top: 10px;margin-bottom: 24px;">
            <div>
              <span v-for="(val,i) in item.class.student" :key="i">{{val.name}} <span v-if="i<item.class.student.length-1">，</span>  </span>
            </div>
            <div>{{item.class.name}}</div>
            <div>{{item.start_time|dayc|weeks}} <span style="color:#999">{{item.class_start_time}} ~ {{item.class_end_time}}</span> </div>
          </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { STable } from '@/components'
import { studentList, studentChangeClass, studentAddList, studentAllotClass } from '@/api/student'
import { classList, studentInClass,checkStudent } from '@/api/class'
import { classing } from '../../../../core/icons'
import { getCourseInfo} from '@/api/config'
export default {
  name: 'classmates',
  methods: {
    //获取课程配置
    getCourseSet(){
        getCourseInfo({
        school_id: this.$store.state.user.school,
        key: 'course_setting'
      })
        .then(res => {
          if(res.value&&JSON.stringify(res.value)!='{}'){
            this.courseCalidity = res.value.valid_time
          }else{
          }
        })
        .catch(err => {
          // this.loading = false
          this.$message.error(err.data.message || '加载失败')
        })
    },
    showMoreStudent() {
      this.visible = true
      this.$nextTick(function () {
        this.$refs.studentTable.refresh(true)
      })
    },
    cancel() {},
    getTable() {
      studentInClass(this.queryParams, Number(this.$route.query.id))
        .then((res) => {
          this.loading = false
          this.loadData = res
        })
        .catch((err) => {
          this.loading = false
          this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
        })
    },
    onSelectChange(selectedRowKeys, data) {
      let arr = []
      data.forEach((val) => {
        arr.push(val.id)
      })
      this.actionAll = arr
      this.selectedRowKeys = selectedRowKeys
    },
    SonSelectChange(e) {
      this.SselectedRowKeys = e
    },
    studentOk(){
      if(this.SselectedRowKeys.length>0){
        studentAllotClass(
          {
            student_ids: this.SselectedRowKeys,
          },
          Number(this.$route.query.id)
        )
          .then((res) => {
            this.$message.success('添加成功')
            this.getTable()
            this.$refs.studentTable.refresh()
          })
          .catch((err) => {
            this.$message.error(err.data.message || '添加失败')
            return
          })
           this.handleCancel()
      }
      if(this.choiceStudents.length>0){
        this.selectClass()
        this.studentVisible=false
      }
       
    },
    handleOk() {
      let that=this
      if (this.SselectedRowKeys.length > 0) {
        checkStudent({
          student_ids: this.SselectedRowKeys,
          class_ids:[this.$route.query.id]
        }).then(res=>{
          if(res.data.length>0){
            this.studentVisible=true
            this.conflict=res.data
          }
          else{
            this.studentOk()
          }
        }).catch(err=>{
           this.$message.error(err.data.message || '冲突检测失败')
        })
      }
    },
    addConflictTest(){
      if (this.SselectedRowKeys.length > 0) {
        checkStudent({
        
          student_ids: this.SselectedRowKeys,
          class_ids:[this.$route.query.id]
        }).then(res=>{

          this.conflict=res.data
        }).catch(err=>{
          this.$message.error(err.data.message || '检测失败')
        })
      }
     if(this.choiceStudents.length>0){
       checkStudent({
          student_ids: this.choiceStudents,
          class_ids:[this.choiceClassID]
        }).then(res=>{

          this.conflict=res.data
        }).catch(err=>{
          this.$message.error(err.data.message || '检测失败')
        })
     }
    },
    handleCancel() {
      this.SselectedRowKeys = []
      this.keywords = undefined
      this.visible = false
       this.studentVisible=false
    },
    remove(e) {
      studentChangeClass({
        from_class_id: Number(this.$route.query.id),
        student_ids: e,
      })
        .then((res) => {
          this.getTable()
          this.$message.success('操作成功')
          this.selectedRowKeys = []
        })
        .catch((err) => {
          this.$message.error(err.data.message || '操作失败')
        })
    },
    showClass(e) {
      if (e) {
        this.choiceStudents = e
        this.loading = true
        classList(
          Object.assign(
            { pageSize: 99999999 },
            {
              course_id: this.course,
              school_id: this.$store.state.user.school,
              not_student_ids: e,
              structures_id: this.structureID,
            }
          )
        )
          .then((res) => {
            this.classSelect = res.data
          })
          .catch((err) => {
            this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
          })
          .finally(() => {
            this.loading = false
            this.classModel = true
          })
      }
    },
    classChoiceCancel() {
      this.classModel = false
      this.choiceClassID = undefined
    },
    selectClass(){
       studentChangeClass({
        from_class_id: Number(this.$route.query.id),
        to_class_id: this.choiceClassID,
        student_ids: this.choiceStudents,
      })
        .then((res) => {
          this.$message.success('操作成功')
          this.selectedRowKeys = []
          this.getTable()
          this.classChoiceCancel()
        })
        .catch((err) => {
          this.$message.error(err.data.message || '操作失败')
        })
    },
    moveClass() {
      checkStudent({
          student_ids: this.choiceStudents,
          class_ids:[this.choiceClassID],
          class_id:Number(this.$route.query.id)
        }).then(res=>{
          if(res.data.length>0){
            this.studentVisible=true
            this.conflict=res.data
          }
          else{
            this.selectClass()
          }
        }).catch(err=>{
           this.$message.error(err.data.message || '冲突检测失败')
        })
    },
  },
  components: {
    STable,
  },
  props: ['course', 'courseName', 'structureID'],
  data() {
    return {
      courseCalidity:false,
      studentVisible:false,
      //冲突数据
      conflict:[],
      loading: false,
      selectedRowKeys: [],
      actionAll: [], //批量操作选中的数据ID
      SconfirmLoading: false,
      SselectedRowKeys: [],
      keywords: undefined,
      studentLoading: false,
      studentColumns: [
        {
          title: '姓名',
          dataIndex: 'name',
          fixed: 'left',
          ellipsis: true,
          align: 'left',
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: 100,
          ellipsis: true,
          align: 'left',
          scopedSlots: { customRender: 'sex' },
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
          ellipsis: true,
          align: 'left',
        },
        {
          title: '消耗课程',
          dataIndex: 'time',
          ellipsis: true,
          align: 'left',
          customRender: (text) => this.courseName,
        },
      ],
      studentLoadData: (parameter) => {
        this.studentLoading = true
        return studentAddList(
          Object.assign(parameter, {
            course_id: this.course,
            keywords: this.keywords,
          }),
          Number(this.$route.query.id)
        )
          .then((res) => {
            this.loading = false
            return res
          })
          .catch((err) => {
            this.loading = false
            this.$message.error(err.data.message || '获取数据失败，请刷新页面或稍后再试')
          })
      },
      classSelect: [],
      classModel: false,
      choiceClassID: undefined,
      choiceStudents: [],
      queryParams: { school_id: this.$store.state.user.school, class_id: Number(this.$route.query.id), type: 1 },
      visible: false,
      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          fixed: 'left',
          ellipsis: true,
          align: 'left',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
          ellipsis: true,
          align: 'left',
        },
        {
          title: '消耗课程',
          dataIndex: 'time',
          ellipsis: true,
          align: 'left',
          customRender: (text) => this.courseName,
        },
        {
          title: '剩余课时/天数',
          dataIndex: 'shengyu',
          ellipsis: true,
          align: 'left',
          scopedSlots: { customRender: 'shengyu' },
        },
        {
          title: '上课状态',
          dataIndex: 'attend_class_type',
          ellipsis: true,
          align: 'left',
          customRender(text) {
            return text == 1 ? '上课中' : text == 2 ? '暂停上课' : ''
          },
        },
        {
          title: '操作',
          width: 200,
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
    }
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
  },
  watch: {
    keywords(val) {
      this.$refs.studentTable.refresh()
    },
  },
  created() {
    this.loading = true
    this.getCourseSet()
    this.getTable()
  },
  // ],
}
</script>

<style lang="less" scoped>
.title{
  display: flex;
  justify-content: space-between;
  margin-bottom:10px;
  .title-left{
      font-weight: bold;
  }
  .title-right{
    color: rgb(255, 255, 255);
    font-size: 12px;
    padding:4px 10px;
    background: rgb(255, 117, 25);
    border-radius: 3px;
  }
}
.datas{
  max-height: 150px;
    background: rgb(255, 255, 255);
    border-width: 1px;
    border-style: solid;
    border-color: rgb(232, 232, 232);
    border-image: initial;
    border-radius: 4px;
    padding: 16px;
    overflow: auto;
 
}
</style>